<script setup lang="ts">
import { ref, reactive } from "vue";
import {
  type FormInstance,
  type FormRules,
  ElMessageBox,
  ElMessage,
} from "element-plus";
import { sumValues } from "@/utils/common";
import Decimal from "decimal.js";

interface RuleForm {
  acceptor: string;
  billAmount: string;
  points: string;
  open: string;
}

// #region 贴现
const discountList = ref<any[]>([]);
const discountLen = ref<number>(0);
const discountRef = ref<FormInstance>();
const discount = reactive({
  acceptor: "",
  matter: "",
  billAmount: "",
  points: "",
  open: 1,
});
const discountTotal = reactive({
  serialNumber: "",
  matter: "",
  acceptor: "",
  billAmount: "",
  points: "",
  open: "",
  rebate: "",
  interestDeduction: "",
});
const discountRules = reactive<FormRules<RuleForm>>({
  acceptor: [{ required: true, message: "请输入承兑人信息", trigger: "blur" }],
  billAmount: [
    { required: true, message: "请输入票面金额（万元）", trigger: "blur" },
  ],
  points: [{ required: true, message: "请输入点数", trigger: "blur" }],
  open: [
    {
      required: true,
      message: "请选择张数",
      trigger: "change",
    },
  ],
});
// #endregion

// #region buy tickets 买票
const buysList = ref<any[]>([]);
const buysLen = ref<number>(0);
const buyRef = ref<FormInstance>();
const buy = reactive({
  acceptor: "",
  billAmount: "",
  points: "",
  open: 1,
});
const buyTotal = reactive({
  serialNumber: "",
  matter: "",
  acceptor: "",
  billAmount: "",
  points: "",
  open: "",
  rebate: "",
  interestDeduction: "",
});
const buyRules = reactive<FormRules<RuleForm>>({
  acceptor: [{ required: true, message: "请输入承兑人信息", trigger: "blur" }],
  billAmount: [
    { required: true, message: "请输入票面金额（万元）", trigger: "blur" },
  ],
  points: [{ required: true, message: "请输入点数", trigger: "blur" }],
  open: [
    {
      required: true,
      message: "请选择张数",
      trigger: "change",
    },
  ],
});
// #endregion

// #region 列表数据变化
const total = reactive({
  acceptor: "",
  billAmount: "",
  points: "",
  open: "",
  rebate: "",
  interestDeduction: "",
});
// 重置total
const resetTotal = () => {
  total.acceptor = "";
  total.billAmount = "";
  total.points = "";
  total.open = "";
  total.rebate = "";
  total.interestDeduction = "";
};

const onTotal = () => {
  resetTotal();
  if (discountLen.value > 0 && buysLen.value == 0) {
    let { billAmount, interestDeduction } = sumValues(discountList.value);
    discountTotal.billAmount = billAmount;
    discountTotal.interestDeduction = interestDeduction;
    total.acceptor = "还需回款金额";
    total.billAmount = discountTotal.billAmount + "元";
    total.open = "合计扣息金额";
    total.interestDeduction = discountTotal.interestDeduction + "元";
  } else if (buysLen.value > 0 && discountLen.value == 0) {
    let { billAmount, interestDeduction } = sumValues(buysList.value);
    buyTotal.billAmount = billAmount;
    buyTotal.rebate = interestDeduction;
    total.billAmount = buyTotal.billAmount + "元";
    total.acceptor = "还需收款金额";
    total.interestDeduction = "合计返点";
    total.rebate = buyTotal.rebate + "元";
  } else if (buysLen.value > 0 && discountLen.value > 0) {
    let totalDis = sumValues(discountList.value);
    discountTotal.billAmount = totalDis.billAmount;
    discountTotal.interestDeduction = totalDis.interestDeduction;
    let totalBuy = sumValues(buysList.value);
    buyTotal.billAmount = totalBuy.billAmount;
    buyTotal.rebate = totalBuy.interestDeduction;

    let billAmountDis = new Decimal(discountTotal.billAmount || 0);
    let billAmountBuy = new Decimal(buyTotal.billAmount || 0);
    let number = billAmountDis.sub(billAmountBuy).toNumber();
    if (number == 0) {
      total.billAmount = "已走平";
    } else if (number > 0) {
      total.acceptor = "还需回款金额";
      total.billAmount = number + "元";
    } else {
      total.acceptor = "还需收款金额";
      total.billAmount = number + "元";
    }

    let discount = new Decimal(discountTotal.interestDeduction || 0);
    let buy = new Decimal(buyTotal.rebate || 0);
    let difference = discount.sub(buy).toNumber();
    if (difference == 0) {
      total.interestDeduction = "已走平";
    } else if (difference > 0) {
      total.open = "合计扣息金额";
      total.interestDeduction = difference + "元";
    } else {
      total.open = "合计返点";
      total.interestDeduction = difference + "元";
    }
  }
};
// #endregion

// #region 公共提交方法
const onSubmit = async (formEl: FormInstance | undefined, type: string) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (type == "discountList") {
        discountLen.value = discountLen.value + 1;
        let points = new Decimal(discount.points || 0);
        points = points.div(100);
        let billAmount = new Decimal(discount.billAmount || 0);
        billAmount = billAmount.mul(10000);
        let disObj = {
          serialNumber: discountLen.value,
          matter: "贴现",
          acceptor: discount.acceptor,
          billAmount: discount.billAmount,
          points: discount.points,
          open: discount.open,
          rebate: "",
          interestDeduction: points
            .mul(discount.open)
            .mul(billAmount)
            .toString(),
        };
        discountList.value.push(disObj);
        if (discountRef.value) {
          discountRef.value.resetFields();
        }
      }
      if (type == "buyList") {
        buysLen.value = buysLen.value + 1;
        let points = new Decimal(buy.points || 0);
        points = points.div(100);
        let billAmount = new Decimal(buy.billAmount || 0);
        billAmount = billAmount.mul(10000);
        let buyObj = {
          serialNumber: buysLen.value,
          matter: "买票",
          acceptor: buy.acceptor,
          billAmount: buy.billAmount,
          points: buy.points,
          open: buy.open,
          interestDeduction: "",
          rebate: points.mul(buy.open).mul(billAmount).toString(),
        };

        buysList.value.push(buyObj);
        if (buyRef.value) {
          buyRef.value.resetFields();
        }
      }
      onTotal();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
// #endregion

const isEditBoolendis = ref<boolean>(false);
const isEditBoolenbuy = ref<boolean>(false);
const selecteddis = ref(-1);
const selectedbuy = ref(-1);
const selectedRowIndex = ref(-1);
const selectedRowType = ref("");
const selectRow = (index: number, type: string) => {
  if (type == "discount") {
    if (discountRef.value) {
      discountRef.value.resetFields();
    }
    let lists = discountList.value[index];
    discount.acceptor = lists.acceptor;
    discount.billAmount = lists.billAmount;
    discount.points = lists.points;
    discount.open = lists.open;
    isEditBoolendis.value = true;
    selecteddis.value = index;
  }
  if (type == "buy") {
    if (buyRef.value) {
      buyRef.value.resetFields();
    }
    let lists = buysList.value[index];
    buy.acceptor = lists.acceptor;
    buy.billAmount = lists.billAmount;
    buy.points = lists.points;
    buy.open = lists.open;
    isEditBoolenbuy.value = true;
    selectedbuy.value = index;
  }

  selectedRowIndex.value = index;
  selectedRowType.value = type;
};
const doEdit = (type: string) => {
  if (type == "discount") {
    let lists = discountList.value[selecteddis.value];
    lists.acceptor = discount.acceptor;
    lists.billAmount = discount.billAmount;
    lists.points = discount.points;
    lists.open = discount.open;
    isEditBoolendis.value = false;
    if (discountRef.value) {
      discountRef.value.resetFields();
    }
  }
  if (type == "buy") {
    let lists = buysList.value[selecteddis.value];
    lists.acceptor = buy.acceptor;
    lists.billAmount = buy.billAmount;
    lists.points = buy.points;
    lists.open = buy.open;
    isEditBoolendis.value = false;
    if (buyRef.value) {
      buyRef.value.resetFields();
    }
  }
};

// #region 功能栏
// Function
// 清空表格
const clear = () => {
  resetTotal();
  buysList.value = [];
  buysLen.value = 0;
  discountList.value = [];
  discountLen.value = 0;
};

// 单个删除
const single = () => {
  if (selectedRowType.value == "discount") {
    discountList.value.splice(selectedRowIndex.value, 1);
    // 使用 map 方法重置新数组的索引
    discountList.value.map((value, index) => {
      value.serialNumber = index + 1;
      return value;
    });
    isEditBoolendis.value = false;
    selecteddis.value = -1;
    discountLen.value = discountList.value.length;
  }
  if (selectedRowType.value == "buy") {
    buysList.value.splice(selectedRowIndex.value, 1);

    // 使用 map 方法重置新数组的索引
    buysList.value.map((value, index) => {
      value.serialNumber = index + 1;
      return value;
    });
    isEditBoolenbuy.value = false;
    buysLen.value = buysList.value.length;
    selectedbuy.value = -1;
  }

  selectedRowIndex.value = -1;
  selectedRowType.value = "";
  onTotal();
};
//保存
const saves = () => {
  ElMessageBox.prompt("请输入企业名称", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(({ value }) => {
      if (value == "") {
        ElMessage({
          type: "error",
          message: "请输入企业名称",
        });
      } else {
        let hisObj = {
          name: value,
          text: JSON.stringify({
            discount: discountList.value,
            buy: buysList.value,
          }),
        };
        historyList.value.push(hisObj);
        discountList.value = [];
        discountLen.value = 0;
        buysList.value = [];
        buysLen.value = 0;
      }
    })
    .catch(() => {
      ElMessage({
        type: "error",
        message: "请输入企业名称",
      });
    });
};
// #endregion

const historyActive = ref<number | null>(-1);
const historyList = ref<any[]>([]);

const handleHistory = (item: any, index: number) => {
  console.log(item);
  if (historyActive.value === index) {
    historyActive.value = null;
  } else {
    historyActive.value = index;
  }
  let hisObj = JSON.parse(item.text);
  discountList.value = hisObj.discount;
  discountLen.value = discountList.value.length;
  buysList.value = hisObj.buy;
  buysLen.value = buysList.value.length;
};

const isCompleteBoolean = ref<boolean>(true);
const special = ref<boolean>(false);
const specialNum = ref<number>(0);
const handleComplete = () => {
  isCompleteBoolean.value = !isCompleteBoolean.value;
  special.value = !special.value;
  let billAmount = new Decimal(discountTotal.billAmount || 0);
  let interestDeduction = new Decimal(discountTotal.interestDeduction || 0);
  specialNum.value = billAmount.sub(interestDeduction).toNumber();
};
</script>

<template>
  <div>
    <div class="calculator">
      <div class="calculator-enter">
        <div class="calculator-enter-headr">
          <div class="discount">
            <div class="discount-title">贴现</div>
            <div class="discount-item">
              <el-form
                :inline="true"
                :model="discount"
                class="demo-form-inline form-inline"
                label-position="top"
                ref="discountRef"
                :rules="discountRules"
              >
                <el-form-item label="承兑人信息" prop="acceptor">
                  <el-input
                    v-model="discount.acceptor"
                    placeholder="承兑人信息"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="票面金额（万元）" prop="billAmount">
                  <el-input
                    v-model="discount.billAmount"
                    placeholder="票面金额（万元）"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="点数" prop="points">
                  <el-input
                    v-model="discount.points"
                    placeholder="点数"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="张数" prop="open">
                  <el-select
                    v-model="discount.open"
                    placeholder="张数"
                    clearable
                    style="width: 80px"
                  >
                    <el-option
                      v-for="number in 10"
                      :key="number"
                      :label="number"
                      :value="number"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button
                    v-if="!isEditBoolendis"
                    type="primary"
                    @click="onSubmit(discountRef, 'discountList')"
                    >添加</el-button
                  >
                  <el-button v-else type="primary" @click="doEdit('discount')"
                    >修改</el-button
                  >
                  <el-button @click="resetForm(discountRef)">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
            <div class="discount-title">买票</div>
            <div class="discount-item">
              <el-form
                :inline="true"
                :model="buy"
                class="demo-form-inline form-inline"
                label-position="top"
                ref="buyRef"
                :rules="buyRules"
              >
                <el-form-item label="承兑人信息" prop="acceptor">
                  <el-input
                    v-model="buy.acceptor"
                    placeholder="承兑人信息"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="票面金额（万元）" prop="billAmount">
                  <el-input
                    v-model="buy.billAmount"
                    placeholder="票面金额（万元）"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="点数" prop="points">
                  <el-input v-model="buy.points" placeholder="点数" clearable />
                </el-form-item>
                <el-form-item label="张数" prop="open">
                  <el-select
                    v-model="buy.open"
                    placeholder="张数"
                    clearable
                    style="width: 80px"
                  >
                    <el-option
                      v-for="number in 10"
                      :key="number"
                      :label="number"
                      :value="number"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="onSubmit(buyRef, 'buyList')"
                    v-if="!isEditBoolenbuy"
                    >添加</el-button
                  >
                  <el-button type="primary" @click="doEdit('buy')" v-else
                    >修改</el-button
                  >
                  <el-button @click="resetForm(buyRef)">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="function">
            <div>功能</div>
            <div class="function-item">
              <div class="function-button">
                <el-button type="primary" @click="clear">清空表格</el-button>
              </div>
              <div class="function-button">
                <el-button type="primary" @click="single">单个删除</el-button>
              </div>
              <div class="function-button">
                <el-button type="primary" @click="saves">保存</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="calculator-enter-body">
          <table>
            <thead>
              <tr>
                <th>序号</th>
                <th>事项</th>
                <th>承兑人信息</th>
                <th>票面金额(万元)</th>
                <th>点数</th>
                <th>张数</th>
                <th>扣息金额</th>
                <th>返点</th>
              </tr>
            </thead>
            <tbody>
              <template v-if="discountLen > 0">
                <tr
                  v-for="(item, index) in discountList"
                  :key="index"
                  @click="selectRow(index, 'discount')"
                  :class="{
                    selected:
                      index === selectedRowIndex &&
                      selectedRowType == 'discount',
                  }"
                >
                  <td>{{ item.serialNumber }}</td>
                  <td>{{ item.matter }}</td>
                  <td>{{ item.acceptor }}</td>
                  <td>{{ item.billAmount }}</td>
                  <td>{{ item.points }}</td>
                  <td>{{ item.open }}</td>
                  <td>{{ item.interestDeduction }}</td>
                  <td>{{ item.rebate }}</td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
              </template>

              <template v-if="buysLen > 0">
                <tr
                  v-for="(item, index) in buysList"
                  :key="index"
                  @click="selectRow(index, 'buy')"
                  :class="{
                    selected:
                      index === selectedRowIndex && selectedRowType == 'buy',
                  }"
                >
                  <td>{{ item.serialNumber }}</td>
                  <td>{{ item.matter }}</td>
                  <td>{{ item.acceptor }}</td>
                  <td>{{ item.billAmount }}</td>
                  <td>{{ item.points }}</td>
                  <td>{{ item.open }}</td>
                  <td>{{ item.interestDeduction }}</td>
                  <td>{{ item.rebate }}</td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
              </template>

              <template v-if="buysLen > 0 || discountLen > 0">
                <tr class="total">
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>{{ total.acceptor }}</td>
                  <td>{{ total.billAmount }}</td>
                  <td>{{ total.points }}</td>
                  <td>{{ total.open }}</td>
                  <td>{{ total.interestDeduction }}</td>
                  <td>{{ total.rebate }}</td>
                </tr>
              </template>
              <template v-else>
                <tr>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
              </template>
              <tr v-if="special && discountLen > 0 && buysLen == 0">
                <td colspan="8">
                  <div class="special">
                    扣息回款: {{ discountTotal.billAmount }} -
                    {{ discountTotal.interestDeduction }} =
                    {{ specialNum }}
                    元
                  </div>
                </td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="calculator-history">
        <div class="history">
          <div class="title">历史记录</div>
          <div class="content">
            <p
              v-for="(item, index) in historyList"
              :key="index"
              class="scrollbar-demo-item"
              :class="{ active: historyActive === index }"
              @click="handleHistory(item, index)"
            >
              {{ item.name }}
            </p>
          </div>
        </div>
        <div class="refund">
          <div class="title">回款方式</div>
          <div class="content">
            <el-button
              type="primary"
              @click="handleComplete"
              v-if="isCompleteBoolean"
              >扣&nbsp;&nbsp;息&nbsp;&nbsp;回&nbsp;&nbsp;款</el-button
            >
            <el-button type="primary" @click="handleComplete" v-else
              >全&nbsp;&nbsp;额&nbsp;&nbsp;回&nbsp;&nbsp;款</el-button
            >
          </div>
        </div>
        <div class="table">
          <div class="title">表格截图</div>
          <div class="content">
            <el-button type="primary">截&nbsp;&nbsp;&nbsp;&nbsp;图</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.calculator {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .calculator-enter {
    width: 80%;
    margin-right: 10px;
    .calculator-enter-body {
      border: 1px solid #ccc;
      // padding: 20px;
      height: 300px;
      overflow: auto; /* 开启滚动条 */
      /* Table style */
      table {
        width: 100%;
        border-collapse: collapse;
      }
      th,
      td {
        padding: 8px;
        border: 1px solid #ddd;
        text-align: left;
      }
      th {
        position: sticky;
        top: 0; /* 标题行固定在顶部 */
        background-color: #f2f2f2;
      }
      /* Hover effect */
      tr:hover {
        background-color: #f5f5f5;
      }
      .total {
        background-color: #134e88;
        color: white;
      }
    }
    .calculator-enter-headr {
      display: flex;
      justify-content: center;
      width: 100%;
      margin-bottom: 10px;
      .discount {
        // width: 100%;
        border: 1px solid #ccc;
        padding: 20px;

        .discount-title {
          font-size: 20px;
          font-weight: 700;
          margin-bottom: 10px;
        }
        .discount-item {
          display: flex;
          width: 100%;
          .form-inline {
            display: flex;
            align-items: flex-end;
          }
        }
      }
      .function {
        margin-left: 10px;
        padding: 20px;
        border: 1px solid #ccc;
        width: 10%;
        .function-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          .function-button {
            padding-top: 10px;
          }
        }
      }
    }
  }

  .calculator-history {
    width: 20%;
    .history {
      border: 1px solid #ccc;
      margin-bottom: 10px;
      padding: 10px;
      .title {
        font-size: 20px;
        font-weight: 700;
        margin-bottom: 10px;
      }
      .content {
        height: 324px;
        overflow: auto; /* 开启滚动条 */
        background-color: #efefef;
        .active {
          background-color: #f5f5f5;
        }
      }
    }
    .refund {
      padding: 10px;
      border: 1px solid #ccc;
      margin-bottom: 10px;
      .title {
        font-size: 20px;
        font-weight: 700;
        margin-bottom: 10px;
      }
      .content {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .table {
      padding: 10px;
      border: 1px solid #ccc;
      .title {
        font-size: 20px;
        font-weight: 700;
        margin-bottom: 10px;
      }
      .content {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
.selected {
  background-color: #f0f0f0;
}
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.special {
  display: flex;
  align-items: center;
  justify-content: center;
  color: red;
  font-size: 20px;
}
</style>
